<?php

namespace App\Listeners;

use App\Helpers\PayTrait;
use App\Http\Controllers\Plugin\Models\Java\ShSecret;
use App\Models\Class\Book;
use App\Models\Map\Mch;
use App\Models\Map\ShopGoods;
use App\Models\Map\ShopGoodsSaleLog;
use App\Models\Order\FailEvent;
use App\Models\Order\OrderFlow;
use App\Models\User;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;

// 普通订单支付
class DefaultCommissionListener implements ShouldQueue
{
    use PayTrait;
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  object  $event
     * @return void
     */
    public function handle($event)
    {
        $order = $event->order;
        $checkOrder = $event->checkorder;
        if($order&&$order->real_price>0){
            // $area_code = Mch::query()->where('id',$order->mch_id)->value('area_code');
            $data = [
                'totalAmount'=>$order->real_price,
                'productId'=>[
                    [
                        'goods_id'=>$this->setGoodsId($order),
                        'payMoney'=>$order->source_price*$order->quantity,
                        'goods_num'=>$order->quantity,
                        'price'=>$order->real_price*$order->commission_rate,
                        'goods_price'=>$order->source_price,
                        'create_time'=>time(),
                        'order_id'=>$order->out_trade_no,
                        'area'=> $order->address_code==0?'320102':$order->address_code,//$order->address_code,
                        'share'=> $order->temp_openid??'',
                    ]
                ],
                'orderId'=>$order->out_trade_no,
                'paymentMethod'=>$order->pay_type,
                'userId'=>$order->openid
            ];

            if(isset($checkOrder['attach'])&&$checkOrder['attach']=='1'){
                $response = Http::post(env('COMMISSION_URL').'/pay_divide/createOrders/', $data);
                $last = $response->body();
                if($last){
                    // 事件错误日志
                    $result = json_decode($last,true);
                    if($result&&isset($result['code'])&&$result['code'] !== 20000){
                        $err['id'] = $order->id;
                        $err['order'] = $order;
                        $err['order_table'] = $event->order_table??'shop_orders';
                        $err['error'] = $last;
                        FailEvent::query()->create($err);
                    }
                }
                // 设置流水账号
                $this->setOrderFlow($order,$checkOrder);
                // 设置订单状态
//                ShOrder::query()->where('order_id',$order->out_trade_no)->update(['order_status'=>10]);
//                PdOrder::query()->where('order_id',$order->out_trade_no)->update(['order_status'=>10]);
                $order_status = [
                    'status'=>10,
                    'order_sn'=>$order->order_sn,
                    'order_id'=>$order->out_trade_no,
                ];

                $response = Http::post(env('COMMISSION_API').'/Api/statusActivity/', $order_status);
                $last = $response->body();
                // 支付成功后减库存
                $this->decIncrementQuantity($order->goods_id,$order->quantity);
                // 增加商品日志
                $goodsLog = ShopGoodsSaleLog::query()
                    ->where('status',1)
                    ->where('goods_id',$order->goods_id)->first();
                if($goodsLog){
                    $goodsLog->increment('sale_quantity');
                }else{
                    $shopdata['goods_id'] = $order->goods_id;
                    $shopdata['sale_quantity'] = 1;
                    ShopGoodsSaleLog::query()->create($shopdata);
                }
            }else{
                $response = Http::post(env('COMMISSION_API').'/Api/paySuccess2/', $checkOrder);
                $last = $response->body();
                $orderFlow = OrderFlow::query()->where('out_trade_no',$checkOrder['out_trade_no'])->first();
                if($orderFlow){
                    $this->setMchBanlance($orderFlow);
                }else{
                    info('未找到订单流水'.json_encode($checkOrder));
                }
            }
            $openid = $order->openid;
            $user_id = cache()->remember('users'.$openid, 1800, function ()use($openid) {
                return User::query()->where('openid',$openid)->value('id');
            });
            if($order->is_mch_code==2){
                if($order->mch_code_num>0){
                    for($i=0;$i<$order->quantity;$i++){
                        $this->setRegisterMchCode($order,$user_id,$order->mch_code_num,1);
                    }

                }
            }
            if($order->is_class_code==2){
                if($order->class_code){
                    for($i=0;$i<$order->quantity;$i++){
                        info('课程码'.$order->class_code);
                        $arr = json_decode($order->class_code,true);

                        if(count($arr)>0){
                            foreach ($arr as $item){
                                $this->setRegisterCode($order,$user_id,$item['num'],2,$item['value']);
                            }
                        }
                    }

                }
            }
        }
    }
    // 配置注册码
    protected function setRegisterMchCode($order,$user_id,$number,$type){
        for($i = 0;$i<$number;$i++){
            $code = $this->setRadom($type);
            $data[$i]['buy_id'] = $user_id;
            $data[$i]['use_id'] = 0;
            $data[$i]['code'] = $code;
            $data[$i]['expire'] = now()->addYears(1);
            $data[$i]['register_type'] = $type;
            $data[$i]['order_sn'] = $order->order_sn;
            // 创建外部订单
            $map['order_id'] = $order->out_trade_no;
            $map['secret_id'] = $code;
            $map['type'] = $type;
            $map['status'] = 0;
            $map['openid'] = $order->openid;
            $map['nid'] = $user_id;
            ShSecret::query()->create($map);
        }
        DB::table('register_codes')->insert($data);
    }
    protected function setRegisterCode($order,$user_id,$number,$type,$class_id=0){
        for($i = 0;$i<$number;$i++){
            $code = $this->setRadom($type);
            $data[$i]['buy_id'] = $user_id;
            $data[$i]['use_id'] = 0;
            $data[$i]['code'] = $code;
            $data[$i]['expire'] = now()->addDays(1);
            $data[$i]['register_type'] = $type;
            $data[$i]['class_id'] = $class_id;
            $data[$i]['order_sn'] = $order->order_sn;
            $data[$i]['class_name'] = $this->getClassName($class_id)->title;
            $data[$i]['goods_image'] = $this->getClassName($class_id)->cover;
            // 创建外部订单
            $map['order_id'] = $order->out_trade_no;
            $map['secret_id'] = $code;
            $map['type'] = $type;
            $map['status'] = 0;
            $map['openid'] = $order->openid;
            $map['nid'] = $user_id;
            ShSecret::query()->create($map);
        }

        DB::table('register_codes')->insert($data);
    }
    protected function getClassName($id){
        return Book::query()->where('id',$id)->select('title','cover')->first();
    }
    protected function setRadom($str=1){
        if($str==1){
            return 'rz_'.Str::random(16).time();
        }else{
            return 'kc_'.Str::random(16).time();
        }
    }
   // 获取课程id
    protected function setGoodsId($order){
        if($order->goods_type==2){
            return '1111'.$order->course_id;
        }else{
            return '1112'.$order->goods_id;
        }
    }
    protected function setOrderFlow($order,$checkOrder){
        $amount = $checkOrder['amount']['total']/100;
        $flow = [
            'openid'=>$order->openid,
            'order_sn'=>$order->order_sn,
            'sub_mchid'=>$order->sub_mchid,
            'commission_rate'=>$order->commission_rate??0,
            'out_trade_no'=>$order->out_trade_no,
            'transaction_id'=>$checkOrder['transaction_id'],
            'real_price'=>$amount,
            'mch_id'=>$order->mch_id,
            'goods_id'=>$order->goods_id,
            'pay_type'=>1,
            'status'=>1,
            'commission_price'=>$amount*$order->commission_rate
        ];
        $res = OrderFlow::query()->create($flow);
        $this->setMchBanlance($res);
    }


    // 服务商代理支付
    protected function decIncrementQuantity($id,$number){
        $goods = ShopGoods::query()->select('is_purchase')->find($id);
        if($goods && $goods->is_purchase==1){
            $res = $goods->decrement('quantity',$number);
        }
    }
}
